const fs = require('fs');
const ospath = require('path')
const {exec, spawn} = require('child_process')
const ffmpeg = 'ffmpeg'

// function readAsBlob(f) {
//     return new Promise((resolve, reject) => {
//         const reader = new FileReader()
//         reader.readAsArrayBuffer(f)
//         reader.onload = r => {
//             resolve(r.target.result)
//         }
//     })
// }
// async function onChooseFile(e) {
//     let files = [...e.target.files]
//     const res = []
//     files.sort((a,b) => a.name.localeCompare(b.name))
//     console.log(files)
//     try {
//         await files.reduce(async (f, c) => {
//             await f
//             const d = await readAsBlob(c)
//             res.push(d)
//
//         }, Promise.resolve())
//         console.log(res)
//         let link$ = document.createElement('a')
//         let blob = new Blob(res, { type: 'video/webm' })
//         link$.setAttribute('download', 'tttt.webm')
//         link$.setAttribute('href', URL.createObjectURL(blob))
//         link$.click()
//     }catch (e) {
//         console.log(e)
//     }
//
// }

async function mergeFiles(filePaths) {
    try {

        const files = fs.readdirSync(filePaths)
            .filter(file => file.endsWith('.webm') && !file.endsWith('merge.webm'))
            .sort((a, b) => a.localeCompare(b));
        let name = files[0].split('.')[0]
        name = name.replace(/ /g, '')
        const outputPath = ospath.join(filePaths, name + 'merge.webm');
        const mergeSavePath = ospath.join(filePaths, name + '.mp4');
        const writeStream = fs.createWriteStream(outputPath);

        for (const file of files) {
            const filePath = ospath.join(filePaths, file);
            await new Promise((resolve, reject) => {
                const readStream = fs.createReadStream(filePath);
                readStream.pipe(writeStream, {end: false});
                readStream.on('end', e=> {
                    resolve(e)
                    fs.unlinkSync(filePath)
                });
                readStream.on('error', reject);
            });
        }
        writeStream.end();
        const res = [];
        // Sort files by name
        // Read all files sequentially
        // for (const filePath of dirs) {
        //     const buffer = fs.readFileSync(ospath.join(filePaths, filePath));
        //     res.push(buffer);
        // }
        // // Create a merged buffer
        // const mergedBuffer = Buffer.concat(res);
        // // Write the merged file
        // await fs.writeFileSync(outputPath, mergedBuffer);
        console.log(`Merged file saved to ${outputPath}`);
        // dirs.forEach(d=> fs.unlinkSync(ospath.join(filePaths, d)))
        const cmd = `  -i ${outputPath} -c:v copy -c:a copy -strict -2   -y ${mergeSavePath}`
        console.log(cmd)
        const ffmpegProcess = spawn(ffmpeg, cmd.split(' '), {
            stdio: ['ignore', 'pipe', 'pipe'], // 忽略 stdin，监听 stdout 和 stderr
            // cwd: savePath, // 明确工作目录
            shell: true // 允许 shell 解析路径 不加可能会出现路径错误
        })

        ffmpegProcess.stdout.on('data', (data) => {
            console.log(`stdout: ${data}`)
        })
        let buff = 0
        ffmpegProcess.stderr.on('data', (data) => {
            console.log(String(data))
        })
        ffmpegProcess.on('close', (code) => {
            fs.unlinkSync(outputPath)
        })
    } catch (e) {
        console.error(e);
    }
}

mergeFiles('D:\\Nginx\\file\\uu')
